package com.graduation.mathematics.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.graduation.mathematics.R;

/**
 * Created by apc_allen
 * date : 2/13/21
 * description :
 */
public abstract class BaseDialogFragment extends DialogFragment {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCancelable(canCancelOutSite());
        if (getArguments() != null) {
            parseData(getArguments());
        }

    }

    @Override
    public void show(@NonNull FragmentManager manager, @Nullable String tag) {
        try {
            super.show(manager, tag);
        } catch (Exception e) {
            //在activity onSaveInstanceState()后弹出弹窗
            if (e instanceof IllegalStateException) {
                FragmentTransaction fragmentTransaction = manager.beginTransaction();
                if (isAdded()) {
                    fragmentTransaction.show(this);
                } else {
                    fragmentTransaction.add(this, tag);
                }
                fragmentTransaction.commitAllowingStateLoss();
            }
        }

    }

    @Override
    public void dismiss() {
        super.dismissAllowingStateLoss();
    }

    protected boolean canCancelOutSite(){
        return false;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(getLayout(), container, false);

    }

    public void onSetStyle(){
        setStyle(STYLE_NORMAL, R.style.RobotBaseDialog);
    }

    protected abstract int getLayout();

    protected abstract void initView(View view);

    protected abstract void parseData(Bundle arguments);

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }
}
